package myoa

import myoa.permission.ActionNameObj
import myoa.permission.ControllerNameObj
import myoa.permission.PermissionSetting
import org.codehaus.groovy.grails.commons.DefaultGrailsControllerClass
import org.codehaus.groovy.grails.commons.GrailsApplication

class PermissionService {
    GrailsApplication grailsApplication

    PermissionSetting getPermissionSetting() {
        List<ControllerNameObj> re = []
        grailsApplication.controllerClasses.each {
            DefaultGrailsControllerClass controllerClass = (DefaultGrailsControllerClass) it

            //ignore authController which is ignored by Shiro Plugin
            if (controllerClass.packageName == 'myoa' && controllerClass.logicalPropertyName != 'auth') {
                Set<String> actionNameSet = []
                controllerClass.getURIs().each {
                    String actionName = controllerClass.getMethodActionName(it)
                    actionNameSet << actionName
                }
                ControllerNameObj controllerNameObj = new ControllerNameObj(controllerClass.logicalPropertyName, actionNameSet.toList())
                re << controllerNameObj
            }
        }
        return new PermissionSetting(re)
    }

    PermissionSetting reviewPermission() {
        PermissionSetting review = getPermissionSetting()
        Role.list().each { role ->
            PermissionSetting view = getPermissionSetting()
            view.grant(role)
            view.setting.each { conNameObj ->
                conNameObj.actionNameObjList.each { actNameObj ->
                    if (actNameObj.allowed) {
                        ActionNameObj find = review.find(conNameObj, actNameObj)
                        find.roleList << role
                    }
                }
            }
        }
        return review
    }
}
